package com.infra.micro.oss.domain.client;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.infra.micro.oss.domain.config.OssConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;

@Component
@Order
public class OssClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(OssClient.class);
    @Resource
    private OssConfig ossConfig;
    private OSS instance;

    public void setInstance(OSS instance) {
        this.instance = instance;
    }

    public OSS getInstance() {
        if (instance == null) {
            setInstance(new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()));
        }
        return instance;
    }

    public PutObjectResult putObject(String key, InputStream inputStream) {
        return getInstance().putObject(ossConfig.getBucketName(), key, inputStream);
    }

    public InputStream getFileObject(String key) {
        OSSObject ossObject = getInstance().getObject(ossConfig.getBucketName(), key);
        return ossObject.getObjectContent();
    }

    public void removeObject(String key) {
        try {
            getInstance().deleteObject(ossConfig.getBucketName(), key);
        } catch (Exception ex) {
            LOGGER.error("删除key:{}时异常", key, ex.getMessage());
        }
    }
}
